package com.kfm.base.thread.day04;

public class Demo02 {

    public static void main(String[] args) {
        Num num = Num.getNum();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                num.odd();
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                num.even();
            }
        }).start();
    }
}

class Num {
    private static int i = 0;
    private static int num = 1;

    private static final Num NUM = new Num();
    private Num(){
        if (NUM != null){
            throw new RuntimeException("单例");
        }
    }

    public static Num getNum(){
        return NUM;
    }

    public synchronized void odd(){
        if (i == 1){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(num ++);
        i = 1;
        notify();
    }

    public synchronized void even(){
        if (i == 0){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(num ++);
        i = 0;
        notify();
    }
}
